package com.cs.widgetvp.fragment;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.cs.base.BaseFragment;
import com.cs.base.adapter.BaseFragmentStateAdapter;
import com.cs.base.util.LogCat;
import com.cs.base.vm.BaseViewModel;
import com.cs.widgetvp.databinding.FragmentGetherBinding;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: GetherFragment
 * @Date: 2021/6/17
 * @Author: CS
 * @Description: 组件功能集合
 */
public class GetherFragment extends BaseFragment<BaseViewModel, FragmentGetherBinding> {

    //顶部Tab栏
    private final String[] tableTitles = new String[]{"推荐","热门","图片","新闻"};
    private final List<Fragment> fragments = new ArrayList<>();

    @Override
    protected FragmentGetherBinding getViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return FragmentGetherBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initView() {
        initTableLayout();
        initViewPage();
    }

    @Override
    protected void initData() {

    }

    /**
     * 初始化首页Tab栏
     */
    private void initTableLayout(){
        LogCat.e("HomeFragment","initTableLayout");
        for(int i=0;i<tableTitles.length;i++){
            binding.getherTl.addTab(binding.getherTl.newTab());
            binding.getherTl.getTabAt(i).setText(tableTitles[i]);
        }
        binding.getherTl.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                binding.getherVp.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
    }

    /**
     * 初始化首页ViewPage
     */
    private void initViewPage(){
        if(fragments.size()>0){
            return;
        }
        fragments.add(new GetherSubFragmentFirst());
        fragments.add(new GetherSubFragmentSecond());
        fragments.add(new GetherSubFragmentThird());
        fragments.add(new GetherSubFragmentFourth());
        BaseFragmentStateAdapter adapter = new BaseFragmentStateAdapter(getActivity(),fragments);
        binding.getherVp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                binding.getherTl.selectTab(binding.getherTl.getTabAt(position));
            }
        });
        binding.getherVp.setUserInputEnabled(true); //true:滑动，false：禁止滑动
        binding.getherVp.setAdapter(adapter);
    }

}